package com.library.service.impl;

import java.io.File;
import java.util.List;

import com.library.bean.Book;
import com.library.bean.Page;
import com.library.dao.BookDao;
import com.library.dao.impl.BookDaoImpl;
import com.library.service.BookService;


public class BookServiceImpl implements BookService {

	private BookDao bookDao = new BookDaoImpl();

	@Override
	public Page<Book> getAllBook(int pageNum, int pageSize) {
		List<Book> bookList = bookDao.selectAllBook(pageNum, pageSize);
		int  totalRows = bookDao.selectBookNum();
		return new Page<Book>(bookList, pageNum, pageSize, totalRows);
	}
	
	@Override
	public int insertBook(Book book) {
		// TODO Auto-generated method stub
		return bookDao.insertBook(book);
	}
	@Override
	public int delBook(int bookId) {
		//删除图书之前 删除图书的封面。
		Book book = bookDao.selectBookById(bookId);
		if(book != null) {
			String path = book.getBookCover();
			///library01/bookCover/book_1683716713092_2.jpg
			int index = path.lastIndexOf("/"); //找到路径名中最后一个"/" 后面即为文件名
			String name = path.substring(index+1);//截取 文件名字
			String realpath  = "c:/bookCoverImgs/"+name;//截取真实路径
			File file = new File(realpath);
			if(file.exists() && !"default.webp".equals(name)) {
				file.delete();//删除文件
			}
		}
		return bookDao.deleteBook(bookId);
	}
	@Override
	public Book getBookById(int bookId) {
		return bookDao.selectBookById(bookId);
	}
	@Override
	public int updateBook(Book book) {
		return bookDao.updateBook(book);
	}
	@Override
	public List<Book> getBooks(String bookName) {
		// TODO Auto-generated method stub
		return bookDao.selectBook(bookName);
	}

	@Override
	public Page<Book> getAllBook(String bookName, int pageNum, int pageSize) {
		List<Book> bookList = bookDao.selectAllBook(bookName,pageNum, pageSize);
		int  totalRows = bookDao.selectBookNum(bookName);
		System.out.println(totalRows);
		return new Page<Book>(bookList, pageNum, pageSize, totalRows);
	}
	

}
